from student import *


class StudentManager:
    def __init__(self):
        self.student_list = []  # 存储数据

    def run(self):
        # 1加载数据
        self.load_student()
        while True:
            self.show_menu()
            menu_num = int(input('请输入功能序号:'))
            if menu_num == 1:
                # 添加
                self.add_student()
            elif menu_num == 2:
                # 删除
                self.del_student()
            elif menu_num == 3:
                # 修改
                self.modify_student()
            elif menu_num == 4:
                # 查询
                self.search_student()
            elif menu_num == 5:
                # 显示所有
                self.show_all_student()
            elif menu_num == 6:
                # 保存
                self.save_student()
            elif menu_num == 7:
                # 退出系统
                print("已退出系统")
                break

    def load_student(self):
        try:
            f = open('student.data','r')
        except:
            f = open('student.data','w')
        else:
            # 没有异常
            data = f.read()
            new_list = eval(data)  # 字典转列表
            self.student_list = [Student(i['name'],i['gender'],i['tel']) for i in new_list]
        finally:
            f.close()

    @staticmethod
    def show_menu():
        print('1.添加学员')
        print('2.删除学员')
        print('3.修改学员')
        print('4.查询学员')
        print('5.显示所有学员')
        print('6.保存')
        print('7.退出系统')

    def add_student(self):
        name = input('请输入姓名:')
        gender = input('请输入性别:')
        tel = input('请输入手机号:')
        student = Student(name, gender, tel)
        self.student_list.append(student)

    def del_student(self):
        name = input('请输入姓名:')
        for i in self.student_list:
            if i.name == name:
                self.student_list.remove(i)
                break
        else:
            print('查无此人')

    def modify_student(self):
        name = input('请输入姓名:')
        for i in self.student_list:
            if i.name == name:
                i.tel = input('请输入要修改的手机号:')
                print(f'修改成功姓名{i.name}-性别{i.gender}-手机号{i.tel}')
                break
        else:
            print('查无此人')

    def search_student(self):
        name = input('请输入姓名:')
        for i in self.student_list:
            if i.name == name:
                print(i)
                break
        else:
            print('查无此人')

    def show_all_student(self):
        for i in self.student_list:
            print(i)

    def save_student(self):
        f = open('student.data', 'w')
        # __dict__ 对象属性转字典
        new_list = [i.__dict__ for i in self.student_list]
        f.write(str(new_list))
        f.close()
